// 路由拦截逻辑
import router from "./router";
import helper from "@/helper/helper";
import store from "@/store";
import NProgress from "nprogress";
import config from "./helper/config";

NProgress.configure({ showSpinner: false });
const white = ["login", "index", "403", "Register"];
router.beforeEach(async (to, from, next) => {
  next();
  NProgress.start();
  // 从统一认证中心跳转处理
  if (to.query.code) {
    const params = {
      code: to.query.code,
      client_id: config.clientId,
      client_secret: config.clientSecret,
      redirect_uri: config.redirectUri,
      grant_type: "authorization_code",
    };
    await store.dispatch("getTokenByCode", params);
    delete to.query.code;
    // next({ ...to, replace: true }) // 解决用户信息请求两次
  }
  if (helper.storage.get("portal")) {
    store.replaceState(
      Object.assign({}, store.state, JSON.parse(helper.storage.get("portal")))
    );
    helper.storage.remove("portal");
  }
  if (helper.getToken()) {
    if (to.path === "/login") {
      // 临时处理业务系统退出无法返回门户登录页问题------后续优化TODO
      if (to.query.client_id) {
        store.dispatch("clearStore");
        next();
      } else {
        next({ path: config.systemType === "sso" ? "/sso" : "/" });
      }
      NProgress.done();
    } else {
      // 判断是否获取过用户信息
      if (
        store.getters.roles === undefined ||
        store.getters.roles.length === 0
      ) {
        await store.dispatch("getUserInfo");
      }
      // 解决刷新后store权限路由清空问题
      const routerNames = router.getRoutes().map((item) => item.name);
      // length-1的原因是routerNames里有一个无权限页面的处理路由'*'
      if (routerNames.length - 1 === store.getters.routeNames.length) {
        next();
      } else {
        const roles = store.getters.roles;
        await store.dispatch("GenerateRoutes", roles);
        store.getters.dynamicRoutes.forEach((route) => {
          router.addRoute(route);
        });
        router.addRoute({ path: "*", redirect: "/403" });
        next({ ...to, replace: true });
      }
    }
  } else {
    if (white.indexOf(to.name) > -1) {
      next();
    } else {
      if (config.systemType === "business") {
        const redirectUri = encodeURIComponent(
          "http://" + window.location.host + "/"
        );
        window.location.href = `${config.ssoUrl}/login?client_id=${config.clientId}&redirect_uri=${redirectUri}`;
      } else {
        next({ name: "login" });
      }
      NProgress.done();
    }
  }
});
// 路由守卫
router.afterEach(() => {
  // 关闭浏览器进度条
  NProgress.done();
});
